﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Windows.Data.Xml.Dom;

namespace MicroMVVM.Helpers
{
    public static class XmlSerializerHelper
    {
        /// <summary>
        /// Deserialise a string to an object.
        /// </summary>
        /// <typeparam name="T">Object of type T</typeparam>
        /// <param name="document">XmlDocument</param>
        /// <returns>Object</returns>
        public static T Deserialize<T>(XmlDocument document)
        {
            try
            {
                if (document.DocumentElement == null) return default(T);

                var elementName = document.DocumentElement.NodeName;

                var xml = document.GetXml();

                var bytes = Encoding.UTF8.GetBytes(xml);

                using (var memoryStream = new MemoryStream(bytes))
                {
                    var root = new XmlRootAttribute {ElementName = elementName, IsNullable = true};

                    var serializer = new XmlSerializer(typeof (T), root);

                    return (T) serializer.Deserialize(memoryStream);
                }
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        /// <summary>
        /// Serialize an object to an XmlDocument
        /// </summary>
        /// <typeparam name="T">Object of type T</typeparam>
        /// <param name="instance">Instance</param>
        /// <returns>XmlDocument</returns>
        public static XmlDocument Serialize<T>(T instance)
        {
            try
            {
                if ((Equals(instance, null)) || (Equals(instance, default(T)))) return new XmlDocument();

                using (var memoryStream = new MemoryStream())
                {
                    using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
                    {
                        var serializer = new XmlSerializer(instance.GetType());

                        serializer.Serialize(streamWriter, instance);

                        var xmlDocument = new XmlDocument();

                        xmlDocument.LoadXml(streamWriter.ToString());

                        return xmlDocument;
                    }
                }
            }
            catch
            {
                return new XmlDocument();
            }
        }
    }
}